<template>
  <div class="pdf-viewer" @wheel="handleWheel">
    <div class="pdf-toolbar">
      <el-button @click="scrollToPage(1)">首页</el-button>
      <el-button @click="scrollToPage(currentPage - 1)" :disabled="currentPage <= 1">上一页</el-button>
      <span style="color: #000;">{{ currentPage }} / {{ totalPages }}</span>
      <el-button @click="scrollToPage(currentPage + 1)" :disabled="currentPage >= totalPages">下一页</el-button>
      <el-button @click="scrollToPage(totalPages)">末页</el-button>
      <!-- <el-button @click="zoomOut" :disabled="scale <= 0.5">缩小</el-button> -->
      <!-- <el-button @click="zoomIn" :disabled="scale >= 3">放大</el-button> -->
      <!-- <span>当前缩放: {{ Math.round(scale * 100) }}%</span> -->
    </div>
    
    <!-- 添加 ref 属性并监听滚动事件 -->
    <div class="pdf-container" v-if="pdfUrl" ref="pdfContainer" @scroll="updateCurrentPage">
      <!-- 多页连续显示 -->
      <div class="pdf-pages">
        <vue-pdf 
          v-for="page in totalPages" 
          :key="page"
          ref="pdfPages"
          :src="pdfSource" 
          :page="page" 
          :scale="scale"
          @loaded="onPageLoaded(page)"
        ></vue-pdf>
      </div>
      <div v-if="loading" class="loading">加载中...</div>
      <div v-if="error" class="error-message">加载失败: {{ error }}</div>
    </div>
    <div v-else class="no-pdf">请加载PDF文件</div>
  </div>
</template>

<script>
import pdf from 'vue-pdf'
import axios from 'axios'

export default {
  name: 'PDFViewer',
  components: {
    'vue-pdf': pdf
  },
  props: {
    pdfUrl: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      loading: true,
      currentPage: 1,
      totalPages: 0,
      scale: 2.0, // 增大默认缩放比例，从1.5改为2.0
      error: null,
      pdfSource: null,
      blobUrl: null, // 存储Blob URL
      loadedPages: new Set() // 跟踪已加载的页面
    }
  },
  watch: {
    pdfUrl(newUrl) {
      if (newUrl) {
        this.loading = true
        this.error = null
        this.currentPage = 1
        this.totalPages = 0
        this.loadedPages.clear()
        
        this.$nextTick(() => {
          // 使用axios加载PDF内容
          this.loadPdfWithAxios(newUrl)
        })
      }
    },
    // 添加scale的watch以确保PDF页面响应缩放变化
    scale(newScale) {
      console.log('缩放级别变更为:', newScale)
      // 可以在这里添加其他缩放相关的处理
    }
  },
  mounted() {
    // 如果组件挂载时已有pdfUrl，则加载PDF
    if (this.pdfUrl) {
      this.loadPdfWithAxios(this.pdfUrl)
    }
    
    // 移除window滚动事件监听
    // window.addEventListener('scroll', this.updateCurrentPage)
  },
  beforeDestroy() {
    // 清理Blob URL和事件监听器
    if (this.blobUrl) {
      URL.revokeObjectURL(this.blobUrl)
      this.blobUrl = null
    }
    // 移除window滚动事件监听
    // window.removeEventListener('scroll', this.updateCurrentPage)
  },
  methods: {
    // 使用axios加载PDF
    loadPdfWithAxios(url) {
      // 先清理之前的Blob URL
      if (this.blobUrl) {
        URL.revokeObjectURL(this.blobUrl)
        this.blobUrl = null
      }
      
      this.loading = true
      this.error = null
      
      // 修改 axios 请求配置
      axios.get(url, {
        responseType: 'blob',
        withCredentials: false,
        headers: {
          'Accept': 'application/pdf'
        },
        timeout: 30000
      })
      .then(response => {
        // 检查是否为PDF文件或有内容
        const blob = response.data
        if (!blob || blob.size === 0) {
          throw new Error('获取的文件为空')
        }
        
        // 验证是否为PDF相关类型
        const isPdfType = blob.type === 'application/pdf' || blob.type === '' || blob.type.includes('pdf')
        if (!isPdfType && blob.type) {
          console.warn('警告: 返回的文件类型不是PDF:', blob.type)
        }
        
        // 创建Blob URL
        this.blobUrl = URL.createObjectURL(blob)
        
        // 使用createLoadingTask加载PDF
        try {
          this.pdfSource = pdf.createLoadingTask({
            url: this.blobUrl,
            withCredentials: false
          })
          
          // 获取总页数
          this.pdfSource.promise.then(pdfDoc => {
            this.totalPages = pdfDoc.numPages
            this.loading = false
          })
        } catch (err) {
          console.error('创建PDF加载任务失败:', err)
          this.error = '创建PDF加载任务失败: ' + err.message
          this.loading = false
        }
      })
      .catch(error => {
        console.error('PDF文件获取失败:', error)
        
        // 提供更详细的错误信息
        if (error.response) {
          this.error = `服务器错误: ${error.response.status} ${error.response.statusText}`
          if (error.response.status === 401) {
            this.error += '（可能需要登录）'
          }
        } else if (error.request) {
          this.error = '网络错误，请检查网络连接或服务器是否可用'
        } else if (error.code === 'ERR_NETWORK') {
          this.error = '网络连接错误，可能是跨域问题或服务器不可达'
        } else {
          this.error = error.message || '未知错误'
        }
        this.loading = false
      })
    },
    
    // 处理页面加载完成
    onPageLoaded(page) {
      this.loadedPages.add(page)
      // 当所有页面加载完成或加载超过5页时，设置loading为false
      if (this.loadedPages.size >= Math.min(this.totalPages, 5)) {
        this.loading = false
      }
    },
    
    // 处理鼠标滚轮事件
    handleWheel() {
      // 阻止默认滚动行为，使用自定义滚动逻辑
      // event.preventDefault()
    },
    
    // 滚动到指定页
    scrollToPage(page) {
      if (page < 1) page = 1
      if (page > this.totalPages) page = this.totalPages
      
      const pdfElement = this.$refs.pdfPages[page - 1]
      if (pdfElement) {
        pdfElement.$el.scrollIntoView({ behavior: 'smooth', block: 'start' })
        this.currentPage = page
      }
    },
    
    // 更新当前页码（基于滚动位置）
    updateCurrentPage() {
      if (!this.$refs.pdfPages || this.$refs.pdfPages.length === 0) return
      
      // 使用容器的滚动位置而不是window的
      const container = this.$refs.pdfContainer
      const scrollPosition = container.scrollTop + container.clientHeight / 3 // 容器顶部加上1/3可视高度作为检测点
      
      // 找到当前可见的页面
      for (let i = 0; i < this.$refs.pdfPages.length; i++) {
        const pageElement = this.$refs.pdfPages[i].$el
        const rect = pageElement.getBoundingClientRect()
        const containerRect = container.getBoundingClientRect()
        
        // 计算元素相对于容器的位置
        const relativeTop = rect.top - containerRect.top + container.scrollTop
        const relativeBottom = relativeTop + rect.height
        
        // 如果页面的上半部分在可视区域内，则认为这是当前页面
        if (relativeTop <= scrollPosition && relativeBottom >= scrollPosition) {
          this.currentPage = i + 1
          break
        }
      }
    },
    
    // 修复放大功能
    zoomIn() {
      console.log('执行放大操作')
      if (this.scale < 3) { // 增加最大缩放限制
        this.scale += 0.2 // 增加每次放大的幅度
        console.log('放大后缩放比例:', this.scale)
      }
    },
    
    // 修复缩小功能
    zoomOut() {
      console.log('执行缩小操作')
      if (this.scale > 0.5) {
        this.scale -= 0.2 // 增加每次缩小的幅度
        console.log('缩小后缩放比例:', this.scale)
      }
    }
  }
}
</script>

<style scoped>
.pdf-viewer {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.pdf-toolbar {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px 20px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
  flex-shrink: 0;
  z-index: 10;
  position: sticky;
  top: 0;
  flex-wrap: wrap;
}

.pdf-container {
  flex: 1;
  overflow: auto;
  padding: 10px; /* 减少内边距从20px到10px */
  background-color: #fafafa;
  position: relative;
}

.pdf-pages {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 800px; /* 将宽度从100%改为800px */
  margin: 0 auto; /* 居中显示 */
}

/* 修改canvas元素样式，确保PDF页面使用固定宽度 */
.pdf-pages >>> canvas {
  margin: 8px 0;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border-radius: 4px;
  width: 800px !important; /* 设置固定宽度为800px */
  height: auto !important;
}

.no-pdf {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 16px;
}

.loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 16px;
  color: #666;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 10px 20px;
  border-radius: 5px;
  z-index: 100;
}

.error-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 16px;
  color: #f56c6c;
  text-align: center;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 10px 20px;
  border-radius: 5px;
}

/* 确保 PDF 内容可见并添加页面间距 */
:deep(.vue-pdf) {
  display: block;
  margin-bottom: 15px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  /* 确保PDF内容正确显示 */
  width: 100%;
  height: auto;
}

/* 添加响应式样式 */
@media (max-width: 768px) {
  .pdf-toolbar {
    gap: 10px;
    padding: 8px 15px;
  }
  
  .pdf-container {
    padding: 10px;
  }
  
  :deep(.vue-pdf) {
    margin-bottom: 10px;
  }
}
</style>